import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/model/market_model/rob_list_model.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_rob_buy/market_rob_buy_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:shimmer/shimmer.dart';

// 抢购数据弹窗
class RobWindowPage extends StatefulWidget {
  final Function(String finish) onCompleted;
  final VoidCallback? onCancel;

  const RobWindowPage({super.key, required this.onCompleted, this.onCancel});

  static Future<void> show(
    BuildContext context, {
    required Function(String) onCompleted,
    VoidCallback? onCancel,
  }) {
    return showDialog(
      context: context,
      barrierDismissible: false,
      useSafeArea: false,
      builder:
          (_) => RobWindowPage(onCompleted: onCompleted, onCancel: onCancel),
    );
  }

  @override
  State<RobWindowPage> createState() => _RobWindowPage();
}

class _RobWindowPage extends State<RobWindowPage> with WidgetsBindingObserver {
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        debugPrint('应用程序可见并响应用户输入。');
        _stopTime();
        break;
      case AppLifecycleState.inactive:
        debugPrint('应用程序处于非活动状态，并且未接收用户输入');
        _stopTime();
        break;
      case AppLifecycleState.paused:
        debugPrint('用户当前看不到应用程序，没有响应');
        _stopTime();
        break;
      case AppLifecycleState.detached:
        debugPrint('该应用程序仍托管在颤振引擎上，但与任何主机视图分离');
        _stopTime();
        break;
      default:
    }
  }

  Timer? _timer;
  String title = '正在疯狂抢购中…';
  MarketRobBuyController controller = Get.find();
  var robList = RxList<RobListModel>([]);
  var firstList = Rx<RobListModel?>(null);
  @override
  void initState() {
    super.initState();
    //定时器
    _timer = Timer.periodic(Duration(seconds: 3), (timer) {
      consoleLog('定时器=====走');
      getdetail();
    });
    WidgetsBinding.instance.addObserver(this); // 添加观察者
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    consoleLog('消除了');
    WidgetsBinding.instance.removeObserver(this); // 添加观察者
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black.withOpacity(0.4),
      child: Obx(() {
        return Center(
          child: Stack(
            children: [
              Container(
                width: 302.px,
                padding: EdgeInsets.fromLTRB(0.px, 76.px, 0.px, 0.px),
                decoration: BoxDecoration(),
                child: Container(
                  width: 302.px,
                  padding: EdgeInsets.fromLTRB(0.px, 0.px, 0.px, 0.px),
                  decoration: BoxDecoration(
                    color: AppColors.backgroundColorGrey2,
                    borderRadius: BorderRadius.circular(12.px),
                    gradient: LinearGradient(
                      colors: [
                        Color.fromRGBO(63, 59, 132, 1),
                        Color.fromRGBO(29, 31, 98, 1),
                      ],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(height: 78.px),
                      SizedBox(
                        height: 25.px,
                        child: Center(
                          child: Text(
                            title,
                            style: TextStyle(
                              fontSize: 21.px,
                              color: AppColors.backgroundColor,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 20.px),
                      Container(
                        width: 268.px,
                        height: 218.px,
                        clipBehavior: Clip.antiAlias,
                        padding: EdgeInsets.fromLTRB(
                          14.px,
                          18.px,
                          14.px,
                          18.px,
                        ),
                        decoration: BoxDecoration(
                          color: AppColors.backgroundColor,
                          borderRadius: BorderRadius.circular(15.px),
                        ),
                        child: SingleChildScrollView(
                          child: Column(
                            children: [
                              if (firstList.value != null)
                                Container(
                                  padding: EdgeInsets.only(bottom: 10.px),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          '${firstList.value?.collectionName ?? '抢购中'}',
                                          style: TextStyle(
                                            fontSize: 14.px,
                                            color:
                                                AppColors.backgroundColorBlack,
                                          ),
                                          textAlign: TextAlign.left,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 70.px,
                                        child: Text(
                                          '#${firstList.value?.tokenId ?? '抢购中'}',
                                          style: TextStyle(
                                            fontSize: 14.px,
                                            color:
                                                AppColors.backgroundColorBlack,
                                          ),
                                          textAlign: TextAlign.center,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 70.px,
                                        child: Text(
                                          firstList.value?.status == 1
                                              ? '已支付'
                                              : firstList.value?.status == 2
                                              ? '正在抢购'
                                              : firstList.value?.status == 3
                                              ? '停止抢购'
                                              : '余额不足',
                                          style: TextStyle(
                                            fontSize: 14.px,
                                            color:
                                                firstList.value?.status == 1
                                                    ? AppColors
                                                        .backgroundColorBlack
                                                    : AppColors.fontColorRed2,
                                          ),
                                          textAlign: TextAlign.right,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ...robList.map((e) {
                                return Container(
                                  padding: EdgeInsets.only(bottom: 10.px),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          '${e.collectionName}',
                                          style: TextStyle(
                                            fontSize: 14.px,
                                            color:
                                                AppColors.backgroundColorBlack,
                                          ),
                                          textAlign: TextAlign.left,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 70.px,
                                        child: Text(
                                          '#${e.tokenId}',
                                          style: TextStyle(
                                            fontSize: 14.px,
                                            color:
                                                AppColors.backgroundColorBlack,
                                          ),
                                          textAlign: TextAlign.center,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      SizedBox(
                                        width: 70.px,
                                        child: Text(
                                          e.status == 1
                                              ? '已支付'
                                              : e.status == 2
                                              ? '正在抢购'
                                              : e.status == 3
                                              ? '停止抢购'
                                              : '余额不足',
                                          style: TextStyle(
                                            fontSize: 14.px,
                                            color:
                                                AppColors.backgroundColorBlack,
                                          ),
                                          textAlign: TextAlign.right,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              }),
                              if (firstList.value == null && robList.isNotEmpty)
                                Shimmer.fromColors(
                                  baseColor: AppColors.backgroundColor,
                                  highlightColor: AppColors.backgroundColorGrey,
                                  child: _loadingW(),
                                ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 24.px),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          GestureDetector(
                            onTap: () {
                              Navigator.of(context).pop();
                              widget.onCancel?.call();
                            },
                            child: Container(
                              width: 134.px,
                              height: 44.px,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(23.px),
                                border: Border.all(
                                  width: 1.px,
                                  color: AppColors.startColor,
                                ),
                              ),
                              child: Center(
                                child: Text(
                                  '关闭抢购',
                                  style: TextStyle(
                                    color: AppColors.startColor,
                                    fontSize: 15.px,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          SizedBox(width: 12.px),
                          if (controller.rightTxt.value == '暂停抢购')
                            GestureDetector(
                              onTap: () {
                                _stopTime();
                              },
                              child: Container(
                                width: 134.px,
                                height: 44.px,
                                decoration: BoxDecoration(
                                  color: AppColors.startColor,
                                  borderRadius: BorderRadius.circular(23.px),
                                  border: Border.all(
                                    width: 1.px,
                                    color: AppColors.startColor,
                                  ),
                                ),
                                child: Center(
                                  child: Text(
                                    '暂停抢购',
                                    style: TextStyle(
                                      color: AppColors.backgroundColorBlack,
                                      fontSize: 15.px,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          if (controller.rightTxt.value == '继续抢购')
                            GestureDetector(
                              onTap: () {
                                _startTime();
                              },
                              child: Container(
                                width: 134.px,
                                height: 44.px,
                                decoration: BoxDecoration(
                                  color: AppColors.startColor,
                                  borderRadius: BorderRadius.circular(23.px),
                                  border: Border.all(
                                    width: 1.px,
                                    color: AppColors.startColor,
                                  ),
                                ),
                                child: Center(
                                  child: Text(
                                    '继续抢购',
                                    style: TextStyle(
                                      color: AppColors.backgroundColorBlack,
                                      fontSize: 15.px,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          if (controller.rightTxt.value == '查看订单')
                            GestureDetector(
                              onTap: () {},
                              child: Container(
                                width: 134.px,
                                height: 44.px,
                                decoration: BoxDecoration(
                                  color: AppColors.startColor,
                                  borderRadius: BorderRadius.circular(23.px),
                                  border: Border.all(
                                    width: 1.px,
                                    color: AppColors.startColor,
                                  ),
                                ),
                                child: Center(
                                  child: Text(
                                    '查看订单',
                                    style: TextStyle(
                                      color: AppColors.backgroundColorBlack,
                                      fontSize: 15.px,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                      SizedBox(height: 16.px),
                    ],
                  ),
                ),
              ),

              if (firstList.value?.status != 4)
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: ImageAssetWidget(
                    imageUrl: 'static/images/market/rob1.png',
                    width: 338.px,
                    height: 187.5.px,
                  ),
                ),
              if (firstList.value?.status == 4)
                Positioned(
                  top: 17.px,
                  left: 58.5.px,
                  child: ImageAssetWidget(
                    imageUrl: 'static/images/market/rob2.png',
                    width: 232.px,
                    height: 156.px,
                  ),
                ),
            ],
          ),
        );
      }),
    );
  }

  Future<void> _stopTime() async {
    consoleLog('消除了');
    controller.rightTxt.value = '继续抢购';
    _timer?.cancel();
    setState(() {
      title = '已暂停抢购';
    });
  }

  Future<void> _startTime() async {
    controller.rightTxt.value = '暂停抢购';
    //定时器
    _timer = Timer.periodic(Duration(seconds: 3), (timer) {
      consoleLog('定时器=====走');
      setState(() {
        // ListRob.insert(0, 'value');
      });
      getdetail();
    });
    setState(() {
      title = '正在疯狂抢购中…';
    });
  }

  //获取详情
  Future<void> getdetail() async {
    List<String> robListid = [];
    for (var element in controller.listChoose) {
      robListid.add('${element.collectionId}');
    }
    http.netFetch<RobListModel>(
      ProductApi.smartPurchase,
      params: {
        'collectionIds': robListid,
        'payPassword': controller.password.value,
      },
      method: Method.post,
      success: (result) {
        if (result.data?.status == 1) {
          robList.add(result.data!);
        } else {
          firstList.value = result.data!;
        }
        if (result.code != 200 || result.data?.status == 3) {
          _stopTime();
          showToast('${result.data?.msg}');
          return;
        }
        if (result.data?.status == 4) {
          controller.rightTxt.value = '余额不足，抢购失败';
          _stopTime();
          return;
        }
      },

      fail: (code, message) {
        _stopTime();
        Navigator.of(context).pop();
      },
    );
  }

  _loadingW() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: [
        Container(
          width: 250.px,
          height: 20.px,
          decoration: BoxDecoration(
            color: AppColors.grey300,
            borderRadius: BorderRadius.circular(4.px),
          ),
        ),
        SizedBox(height: 10.px),
        Container(
          width: 250.px,
          height: 20.px,
          decoration: BoxDecoration(
            color: AppColors.backgroundColorBlack,
            borderRadius: BorderRadius.circular(4.px),
          ),
        ),
        SizedBox(height: 10.px),
        Container(
          width: 250.px,
          height: 20.px,
          decoration: BoxDecoration(
            color: AppColors.backgroundColorBlack,
            borderRadius: BorderRadius.circular(4.px),
          ),
        ),
        SizedBox(height: 10.px),
        Container(
          width: 250.px,
          height: 20.px,
          decoration: BoxDecoration(
            color: AppColors.backgroundColorBlack,
            borderRadius: BorderRadius.circular(4.px),
          ),
        ),
        SizedBox(height: 10.px),
        Container(
          width: 250.px,
          height: 20.px,
          decoration: BoxDecoration(
            color: AppColors.backgroundColorBlack,
            borderRadius: BorderRadius.circular(4.px),
          ),
        ),
        SizedBox(height: 10.px),
        Container(
          width: 250.px,
          height: 20.px,
          decoration: BoxDecoration(
            color: AppColors.backgroundColorBlack,
            borderRadius: BorderRadius.circular(4.px),
          ),
        ),
      ],
    );
  }
}
